var pageii = null;
var grid = null;
$(function() {
	grid = lyGrid({
		pagId : 'paging',
		l_column : [ {
			colkey : "bpid",
			name : "id",
			hide : true
		}, {
			colkey : "bpcode",
			name : "计划单号",
		}, {
			colkey : "bpedemid",
			name : "编制人",
			isSort:true,
		}, {
            colkey : "stockname",
            name : "成品名称",
            isSort:true,
        },{
            colkey : "num",
            name : "计划数量",
            isSort:true,
        },{
			colkey : "bpbillstateid",
		 	name : "状态"
		},
        //     {
        //     colkey : "matterpick",
        //     name : "领料状态"
        // },
         {
			colkey : "depid",
			name : "生产车间"
		},{
		    colkey : "ofid",
            name : "订单编号"
        },{
			colkey : "bpbtime",
			name : "订购日期",
           isSort:true
		},{
            colkey : "bpetime",
            name : "要求日期"
         }],
		jsonUrl : rootPath + '/workOrder/getWorkOrderPage.shtml',
        dymCol:true,
        checkbox : true,
        records: "list",
        checkValue: "bpid",
        serNumber : false,
        totalPages: "pages",
        totalRecords: "total",
        pagecode: '10',
        pageNow : 'pageNum'

	});
	$("#search").click("click", function() {// 绑定查询按扭
		var searchParams = $("#searchForm").serializeJson();// 初始化传参数
		grid.setOptions({
			data : searchParams
		});
	});
	$("#addAccount").click("click", function() {
		addAccount();
	});
	$("#editAccount").click("click", function() {
		editAccount();
	});
	$("#delAccount").click("click", function() {
		delAccount();
	});
});
function editAccount() {
	var cbox = grid.getSelectedCheckbox();
	if (cbox.length > 1 || cbox == "") {
		layer.msg("只能选中一个");
		return;
	}

	pageii = layer.open({
		title : "编辑",
		type : 2,
		area : ["900px", "80%"],
		content : rootPath + '/workOrder/editWorkOrderManagementUI.shtml?id=' + cbox
	});
}
function addAccount() {
	pageii = layer.open({
		title : "新增",
		type : 2,
		area : ["900px", "80%"],
		content : rootPath + '/workOrder/openWorkOrderManagementUI.shtml'
	});
}
function delAccount() {
	var cbox = grid.getSelectedCheckbox();
	if (cbox == "") {
		layer.msg("请选择删除项！！");
		return;
	}
	layer.confirm('是否删除？', function(index) {
		var url = rootPath + '/workOrder/deleteWorkOrder.shtml';
		var s = CommnUtil.ajax(url, {
			ids : cbox.join(",")
		}, "json");
		if (s == "success") {
			layer.msg('删除成功');
			grid.loadData();
		} else {
			layer.msg('删除失败');
		}
	});
}

function exportExcel(excelName){
    // var mytable = "";//需要导出的数据
    var fileName = excelName+".xlsx"

    var cbox = grid.getSelectedCheckbox();
    if (cbox == "") {//没选则导出所有数据
        var mytable = document.getElementById("mytable");//获取table
        var sheet = XLSX.utils.table_to_sheet(mytable);
    } else {//第二种：导出指定的行

        //获取表头标题，就是表中第一行，序号不存在
        var valueTd= document.getElementById ("mytable").rows[0];

        //复制节点
        var clone_valueTd = valueTd.cloneNode(true);
        // debugger;

        //根据选中行，动态拼接table
        // var tableData = "<table><tr>" + valueTd.innerHTML + "</tr>";
        var table = document.createElement('table');
        table.id = "table1";
        table.appendChild(clone_valueTd);//使用原有节点会对原有dom造成影响

        //获取所有表中所有checkbox
        var inputs = document.getElementById("mytable").getElementsByTagName("input");
        console.log("inputs.length:"+inputs.length);
        for(var i=0;i<inputs.length;i++) {//获取选中行
            if (inputs[i].type == "checkbox") {
                if (inputs[i].checked) {
                    var checkedRow = inputs[i];
                    var tr = checkedRow.parentNode.parentNode;
                    var clone_tr = tr.cloneNode(true);//复制
                    console.log(tr.cells[0].innerText);
                    if(tr.cells[0].innerText != ""){//序号不为空则拼接，为空说明是表头标题
                        // tableData += "<tr>" + tr.innerHTML + "</tr>";
                        table.appendChild(clone_tr)
                    }
                    // console.log("为空是表头，不拼接")
                    // console.log("tr...:"+tr);
                }
            }
        }

        // tableData += "</table>";
        // mytable = document.createElement(tableData);
        var sheet = XLSX.utils.table_to_sheet(table);
    }

    openDownloadDialog(sheet2blob(sheet), fileName);
}

function createOrder(){
    var cbox = grid.getSelectedCheckbox();
    if (cbox.length > 1 || cbox == "") {
        layer.msg("只能选中一个");
        return;
    }

    //获取选择的数据
    var cboxIndex = grid.selectRow()[0];
    console.log("..."+cboxIndex.ofid)
    //判断是否已经生成过订单
    if(cboxIndex.ofid != '' && cboxIndex.ofid != null){
        layer.msg("已生成过订单,订单编号为"+cboxIndex.ofid);
        return;
    }

    //生成订单号
    var myDate = getNowFormatDate();
    var orderNum = "OF"+ myDate + getRandomInt(100,1000);
    console.log(orderNum);

    $.ajax({
        type: 'POST',
        url: rootPath +'/workOrder/createOrder.shtml',
        data: {"orderNum":orderNum,"id":cbox[0]},
        dataType:'JSON',
        success:function(data){
            if (data == "success") {
                layer.msg('创建订单成功！')
                grid.loadData();
                return;
            }
        }
    });


}


function getNowFormatDate() {
    var date = new Date();
    var seperator1 = "-";
    var seperator2 = ":";
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    //OF2022-02-12 13:52:30
    var currentdate = year + seperator1 + month + seperator1 + strDate
        + date.getHours() + seperator2 + date.getMinutes()
        + seperator2 + date.getSeconds();
    currentdate= currentdate.replaceAll("-","");
    currentdate= currentdate.replaceAll(":","");
    return currentdate;
}

function getRandomInt(min, max) {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min)) + min; //不含最大值，含最小值
}